<template>
  <div class="page-box">
    <!-- 搜索区域 -->
    <el-collapse-transition>
      <div v-show="showSearchBox" class="search-box">
        <!-- :inline="true" 表单在一行显示 -->
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="账号">
            <el-input v-model.trim="queryParams.login_name" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model.trim="queryParams.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="账号状态">
            <!-- 分类下拉框 v-model的值为当前被选中的el-option的 value 属性值 -->
            <el-select v-model="queryParams.status" clearable placeholder="请选择">
              <el-option label="全部" value="" />
              <el-option label="启用" :value="1" />
              <el-option label="冻结" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="search">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>
    <!-- 工具条区域 -->
    <div class="toolbar-box">
      <el-row type="flex" justify="space-between">
        <div>
          <el-button plain type="primary" icon="el-icon-plus" @click="showDialog = true">新增</el-button>
          <el-button plain type="warning" icon="el-icon-download">导出</el-button>
        </div>
        <div>
          <el-tooltip content="关闭搜索区" placement="top">
            <el-button icon="el-icon-arrow-up" circle @click="showSearchBox = !showSearchBox" />
          </el-tooltip>
          <el-tooltip content="刷新" placement="top">
            <el-button icon="el-icon-refresh" circle />
          </el-tooltip>
          <el-tooltip content="筛选" placement="top">
            <el-button icon="el-icon-menu" circle />
          </el-tooltip>
        </div>
      </el-row>
    </div>
    <!-- 表格区域 -->
    <!-- @selection-change当选择项发生变化时会触发该事件，参数为已选择的数据对象(row)组成的数组 -->
    <div class="table-box">
      <el-table
        :data="list"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="#" width="55" />
        <el-table-column prop="login_name" label="账号" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="rolename" label="角色">
          <template #default="{row}">
            <el-tag>{{ row.rolename[0] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_date" label="创建时间" :show-overflow-tooltip="true" />
        <el-table-column prop="status" label="状态">
          <template #default="{row}">
            <el-switch
              :value="row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="冻结"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-button type="primary" circle icon="el-icon-edit" @click="doEdit(row.id)" />
            <el-button type="danger" circle icon="el-icon-delete" @click="doDel(row.id)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页区域 -->
    <div class="pagination-box">
      <el-row type="flex" justify="end">
        <el-pagination
          background
          :current-page="queryParams.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryParams.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <!-- 新增和编辑弹出对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="showDialog" width="45%" @close="resetForm">
      <el-form ref="form" label-width="120px" :model="formData" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username" :rules="rules.username">
              <el-input v-model="formData.username" style="width:90%" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="formData.mobile" style="width:90%" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password" :rules="formData.id ?[] : rules.password">
              <el-input
                v-model="formData.password"
                style="width:90%"
                :placeholder="formData.id?'留空表示不修改':'请输入密码'"
              />
            </el-form-item>
            <!-- <el-form-item v-else label="密码" prop="password">
              <el-input v-model="formData.password" style="width:90%" placeholder="请输入密码" />
            </el-form-item> -->
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-switch
                v-model="formData.sex"
                :active-value="0"
                :inactive-value="1"
                active-text="男"
                inactive-text="女"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户头像" prop="icon">
              <!-- 此处以formData中advimgsrc是否为空控制上传按钮的渲染，缺点是必须等待上传完成后按钮才会隐藏 -->
              <!-- 使用fileList是否为空也是一样，但是图片上传完成后会上下抖动一次，已找到解决抖动方法，改用fileList -->
              <!-- 使用布尔值变量判断可以在点击上传，图片上传成功前就能隐藏按钮，但麻烦，此处不用 -->
              <el-upload
                action="http://124.223.14.236:8060/admin/common/upload?type=images"
                :headers="{ 'X-Token': this.$store.getters.token}"
                list-type="picture"
                :on-success="handleSuccess"
                :limit="1"
                :before-upload="beforeUpload"
                :class=" {disable: fileList.length} "
                :file-list="fileList"
                :on-remove="handleRemove"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div> -->
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addUser, delUser, editUser, getUserDetail } from '@/api/user/user'
import { getUserList } from '@/api/system/user'
export default {
  data() {
    return {
      // 控制是否显示搜索区
      showSearchBox: true,
      // 控制编辑和新增表单对话框显示
      showDialog: false,
      // 查询参数对象
      queryParams: {
        login_name: '',
        status: '',
        phone: '',
        page: 1,
        limit: 10
      },
      // 表格数据
      list: [],
      // 数据总量 分页器用
      total: 0,
      formData: {
        username: '',
        mobile: '',
        icon: '',
        sex: 0,
        password: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        icon: [{ required: true, message: '请上传用户头像', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      // 存上传文件
      fileList: []
    }
  },
  computed: {
    dialogTitle() {
      return this.formData.id ? '编辑用户' : '新增用户'
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 表格数据初始化
    async initData() {
      const res = await getUserList(this.queryParams)
      this.list = res.data
      this.total = res.count
    },
    // 搜索
    search() {
      this.queryParams.page = 1
      this.initData()
    },
    // 重置搜索
    reset() {
      this.queryParams = {
        sex: '',
        username: '',
        mobile: '',
        page: 1,
        limit: 10
      }
      this.initData()
    },
    // 切换每页显示数量
    handleSizeChange(value) {
      this.queryParams.limit = value
      this.queryParams.page = 1
      this.initData()
    },
    // 切换分页
    handleCurrentChange(value) {
      this.queryParams.page = value
      this.initData()
    },
    // 提交新增和编辑dialog表单
    submit() {
      this.$refs.form.validate(async(isOK) => {
        if (!isOK) return
        if (this.formData.id) {
          await editUser(this.formData)
          this.$message.success('编辑用户成功！')
        } else {
          await addUser(this.formData)
          this.$message.success('新增用户成功！')
        }
        // 刷新表格数据
        this.initData()
        // 关闭dialog自动重置表单
        this.showDialog = false
      })
    },
    async doEdit(id) {
      this.formData = await getUserDetail(id)
      if (this.formData.icon) {
        this.fileList.push({ url: 'http://124.223.14.236:8060/' + this.formData.icon })
      }
      this.showDialog = true
    },
    doDel(id) {
      this.$confirm('确认删除该广告图?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delUser(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        // 处理删除最后一页最后一条数据
        if (this.list.length === 1 && this.queryParams.page > 1) {
          this.queryParams.page--
        }
        // 刷新表格
        this.initData()
      }).catch(() => {
        return false
      })
    },
    // dialog关闭后自动执行，无需手动调用
    resetForm() {
      /*  resetFrom必须绑定close而不是closed,因为如果在弹窗关闭后再清空fileList，在未清空之前再次点击编辑回显图片
       就会出现抖动问题，但是就算使用close，fileList的清空还是不及时，连续点击编辑还是抖动*/
      this.fileList = []
      // 重置表单数据
      this.formData = {
        username: '',
        mobile: '',
        icon: '',
        sex: 0,
        password: ''
      }
      this.$refs.form.clearValidate()
    },
    // 处理图片上传
    handleSuccess(reponse, file, fileList) {
      this.formData.icon = reponse.data.savePath
      // 这种方法图片上传完成时会出现抖动
      // this.fileList = [{ url: 'http://124.223.14.236:8060/' + reponse.data.savePath }]
      // 这两种方法可以解决上传图片抖动的问题
      this.fileList.push(file)
      // this.fileList = fileList
    },
    // 上传之前做限制
    beforeUpload(file) {
      // if (file.size > 2 * 1024 * 1024) {
      //   this.$message.warning('图片大小超过上传限制！')
      //   return false
      // } else {
      // }
    },
    // 移除图片时的回调
    handleRemove(file, fileList) {
      // 将图片从数组中删除
      // console.log(file, fileList)
      // console.log(this.fileList)
      this.fileList = this.fileList.filter(ele => ele.uid !== file.uid)
      // 因为上传按钮隐藏的条件是advimgsrc是否为空，所以删除图片时要将其置空(已改用fileList判断)
      this.formData.icon = ''
    }
  }
}
</script>
<style lang="scss" scoped>
.image-slot-error{
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100px;
      height: 100px;
     color: #909399;
     background-color: #f5f7fa;
}
// 隐藏图片上传按钮
 :deep(.disable .el-upload--picture) {
    display: none;
}
// 能够解决上传和回显图片时的抖动问题
::v-deep .el-list-leave-active {
  transition: none;
}
::v-deep .el-list-leave-to {
  transition: none;
}
</style>
